package org.example.maven.museumuser.interceptors;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.maven.museumuser.common.RedisCommon;
import org.example.maven.museumuser.service.impl.UserDetailsServiceImpl;
import org.example.maven.museumuser.utils.JwtUtils;
import org.example.maven.museumuser.utils.ThreadlocalUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;


import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static org.example.maven.museumuser.domain.pojo.StaticVariable.User_Jwt;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private RedisCommon redisCommon; // 注入 Redis 工具
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private static final List<String> AUTH_PUBLIC = Arrays.asList(
            "/user/login",
            "/user/register",
            "/exhibition",
            "/exhibition/\\d+"
    );


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String path = request.getRequestURI();
        //System.out.println(path);


        // 直接放行公开接口 ✅
        /*if ("/user/register".equals(path) || "/user/login".equals(path)
                ||"/exhibition".equals(path)||"/exhibition/{id}".equals(path)) {
            filterChain.doFilter(request, response);
            return;
        }*/
        // 检查是否匹配免认证路径
        if (isPublicPath(path)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 放行所有以 /test 开头的请求
        if (pathMatcher.match("/test/**", path)) {
            String jwt = parseJwt(request);
            ThreadlocalUtils.set(jwt);
            filterChain.doFilter(request, response);
            //System.out.println("直接通过");
            return;
        }

        try {
            String jwt = parseJwt(request);
            //System.out.println(jwt);
            //System.out.println(User_Jwt+JwtUtils.getJwtUsername(jwt));
            if (jwt != null && JwtUtils.validateJwt(jwt)) {
                if (redisCommon.checkHaveCode(User_Jwt+JwtUtils.getJwtUsername(jwt))) {
                    ThreadlocalUtils.set(jwt);

                    String username = JwtUtils.getJwtUsername(jwt);

                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                    // 将认证信息存入 SecurityContext
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    SecurityContextHolder.getContext().setAuthentication(authentication);

                } else {
                    System.out.println("redis不存在");
                    handleAuthError(response, "登录失效");
                    return;
                }
            } else {
                System.out.println("jwt已过期2");
                handleAuthError(response, "登录失效");
                return;
            }
        } catch (Exception e) {
            System.out.println("jwt已过期1");
            handleAuthError(response, "认证失败: " + e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    private void handleAuthError(HttpServletResponse response, String message) throws IOException {
        SecurityContextHolder.clearContext(); // ✅ 关键：清除安全上下文
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"" + message + "\"}");
    }


    private String parseJwt(HttpServletRequest request) {
        return request.getHeader("Authorization");
    }

    private boolean isPublicPath(String requestPath) {
        System.out.println(requestPath);
        // 1. 检查精确匹配
        if (AUTH_PUBLIC.contains(requestPath)) {
            return true;
        }

        // 2. 检查正则匹配
        for (String pattern : AUTH_PUBLIC) {
            if (pattern.contains("\\")) { // 检测正则表达式
                if (requestPath.matches(pattern)) {
                    return true;
                }
            }
        }

        return false;
    }


}



